package izsla.beans;
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import izsla.entities.Image;
import izsla.entities.Trip;
import izsla.sb.TripManagementLocal;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.EJB;
import org.richfaces.event.UploadEvent;
import org.richfaces.model.UploadItem;

/**
 *
 * @author aki
 */
public class UploadImage {
    private long tripId = -1;

    private ArrayList<Image> newImages;

    @EJB
    private TripManagementLocal tm;


    public UploadImage() {
	newImages = new ArrayList<Image>();
    }

    public long getTripId() {
	return tripId;
    }

    public void setTripId(long tripId) {
	this.tripId = tripId;
    }

    public Trip getTrip() {
	return tm.getTrip(tripId);
    }

    public List<Image> getNewImages() {
	return newImages;
    }

    /**
     * Saves the uploaded new images.
     */
    public String onSave() {
	for(Image img: newImages) {
	    tm.saveImage(img);
	}
	newImages.clear();
	
	return "showtrip";
    }

    /**
     * Uploads the selected images into the database.
     */
    public void onImageUpload(UploadEvent evt) {
        // REQ13
	Trip trip = getTrip();
	for(UploadItem item : evt.getUploadItems()) {
	    Image img = tm.createImage(trip, SessionHelper.getUser());
	    trip = tm.getTrip(trip.getId());

	    try {
		byte[] buff = null;

		if(item.isTempFile()) {
		    FileInputStream in = new FileInputStream(item.getFile());
		    buff = new byte[item.getFileSize()];
		    in.read(buff);
		    in.close();
		}
		else {
		    buff = item.getData();
		}

		img.setImgData(buff);
		img.setImgName(item.getFileName());
		img.setTitle("Image" + img.getId());
		tm.saveImage(img);
		newImages.add(img);
	    }
	    catch(Exception e) {
                System.err.print("Something error happened during image upload!");
	    }


	}
    }
}
